/**
 * FindFriendsActivity.java
 * Copyright2011 PinMeal
 */
package com.pinmeal;




import com.pinmeal.persistent.FriendsEmailAddressesDao;
import com.pinmeal.types.FriendData;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.Filterable;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @author albertma 
 * Jul 9, 2011
 */
public class FindFriendsActivity extends Activity
{
    private final static int  ENTER_GROUP_NAME = 1;
    static String projection[] = new String[]
    { Email._ID,  ContactsContract.Data.DISPLAY_NAME, Email.DATA1 };
    private FriendListAdapter friendsListdAdapter;
    private ContentResolver mContent;
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.find_friends);
        AutoCompleteTextView inputAutoCompleteView = (AutoCompleteTextView)findViewById(R.id.search_text_id);
        
        inputAutoCompleteView.setThreshold(1);
        ContentResolver contentResolver = this.getContentResolver();
        Cursor cursor = contentResolver.query(Email.CONTENT_URI, projection, null, null, Email.DATA1 + " ASC");
        ContactListAdapter autoSearchUserAdapter = new ContactListAdapter(this.getApplication().getApplicationContext(), cursor);
        inputAutoCompleteView.setAdapter(autoSearchUserAdapter);
        ListView listView = (ListView)findViewById(R.id.friends_list);
        friendsListdAdapter = new FriendListAdapter(this.getApplicationContext());
        listView.setAdapter(friendsListdAdapter);
        Button button = (Button)this.findViewById(R.id.add_friend_button);
        button.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                showDialog(ENTER_GROUP_NAME);
            }

        });
        
    }

    
    @Override
    protected Dialog onCreateDialog(int id)
    {
        switch (id)
        {
            case ENTER_GROUP_NAME:
            {
                LayoutInflater layoutInflater = LayoutInflater.from(getApplicationContext());
                ViewGroup viewGroup = (ViewGroup)layoutInflater.inflate(R.layout.create_group_popup, null);
                AlertDialog.Builder alertDlgBuilder = new AlertDialog.Builder(FindFriendsActivity.this);
                alertDlgBuilder.setView(viewGroup);
               
                final AlertDialog alertDlg = alertDlgBuilder.create();
                final Button okButton = (Button)viewGroup.findViewById(R.id.ok_button);
                final EditText groupText = (EditText)viewGroup.findViewById(R.id.groupEditText);
                groupText.addTextChangedListener(new TextWatcher()
                {
                    
                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count)
                    {
                        if(count == 0)
                        {
                            okButton.setEnabled(false);
                            okButton.setClickable(false);
                        }
                        else
                        {
                            okButton.setEnabled(true);
                            okButton.setClickable(true);
                        }
                    }
                    
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after)
                    {
                        // TODO Auto-generated method stub
                        
                    }
                    
                    @Override
                    public void afterTextChanged(Editable s)
                    {
                        // TODO Auto-generated method stub
                        
                    }
                });
                okButton.setOnClickListener(new OnClickListener()
                {
                    
                    @Override
                    public void onClick(View v)
                    {
                        FriendsEmailAddressesDao.getInstance().store(groupText.getText().toString());
                        Toast.makeText(getApplicationContext(), getResources().getString(R.string.save_friends_success), 3000).show();
                        alertDlg.dismiss();
                    }
                });
                Button cancelButton = (Button)viewGroup.findViewById(R.id.cancel_button);
                cancelButton.setOnClickListener(new OnClickListener()
                {
                    
                    @Override
                    public void onClick(View v)
                    {
                        alertDlg.dismiss();
                    }
                });
                return alertDlg;
            }
        }
        
        return null;
    }
    
    class ContactListAdapter extends CursorAdapter implements Filterable
    {
        
        
        private final int emailIndex = 2;
        private final int displayIndex = 1;
        public ContactListAdapter(Context context, Cursor c)
        {
            super(context, c);
            mContent = context.getContentResolver();
        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) 
        {
            final LayoutInflater inflater = LayoutInflater.from(context);
            LinearLayout view = (LinearLayout) inflater.inflate(
                   R.layout.friend_list_item, parent, false);
            ((TextView)view.findViewById(R.id.name_view)).setText(cursor.getString(displayIndex));
            ((TextView)view.findViewById(R.id.email_view)).setText( cursor.getString(emailIndex));
            view.setOnClickListener(new AutoDropDownOnClickListener());
            return view;
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor)
        {
             ((TextView)view.findViewById(R.id.name_view)).setText(cursor.getString(displayIndex));
             ((TextView)view.findViewById(R.id.email_view)).setText( cursor.getString(emailIndex));
        }


        @Override
        public Cursor runQueryOnBackgroundThread(CharSequence constraint)
        {
            Cursor currentCursor = null;
            if (constraint != null)
            {
                String text = constraint.toString();
                if (text != null && text.trim().length() > 0)
                {
                    currentCursor = mContent.query(Email.CONTENT_URI, projection, ContactsContract.Data.DISPLAY_NAME + " LIKE" + " '%"
                            + text + "%'" + " OR " + Email.DATA1 + " LIKE" + " '%" + text + "%'", null, Email.DATA1
                            + " ASC");

                }
            }
            return currentCursor;
        }

       
    }
    
    
    class AutoDropDownOnClickListener implements OnClickListener
    {

        @Override
        public void onClick(View v)
        {
            if(v instanceof LinearLayout)
            {
                 FriendData friendData = new FriendData();
                 LinearLayout listView = (LinearLayout)v;
                 TextView nameView = (TextView)listView.findViewById(R.id.name_view);
                 TextView emailView = (TextView)listView.findViewById(R.id.email_view);
                 friendData.setName(nameView.getText().toString());
                friendData.setEmail(emailView.getText().toString());
                if (!FriendsEmailAddressesDao.getInstance().add(friendData))
                {
                    Toast.makeText(getApplicationContext(), getResources().getString(R.string.already_existed), 3000)
                            .show();
                }
                Button button = (Button) findViewById(R.id.add_friend_button);
                button.setEnabled(true);
                button.setClickable(true);
                friendsListdAdapter.notifyDataSetInvalidated();
                AutoCompleteTextView inputAutoCompleteView = (AutoCompleteTextView) findViewById(R.id.search_text_id);
                inputAutoCompleteView.setText("");
                inputAutoCompleteView.dismissDropDown();
            }
        }
        
    }
    
    class FriendListAdapter extends BaseAdapter
    {
        protected Context context;
       
        public FriendListAdapter(Context context)
        {
            this.context = context;
        }
       
        @Override
        public long getItemId(int position)
        {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            View friendListItem = null;
            FriendData friendData = FriendsEmailAddressesDao.getInstance().get(position);
            if (convertView instanceof LinearLayout)
            {
                friendListItem = (LinearLayout)convertView;
                TextView nameView = (TextView) friendListItem.findViewById(R.id.name_view);
                nameView.setText(friendData.getName());
                TextView emailView = (TextView) friendListItem.findViewById(R.id.email_view);
                emailView.setText(friendData.getEmail());
            }
            else 
            {
                LayoutInflater inflater = LayoutInflater.from(context);
                friendListItem = (LinearLayout) inflater.inflate(R.layout.friend_list_item, null);
                TextView nameView = (TextView) friendListItem.findViewById(R.id.name_view);
                nameView.setText(friendData.getName());
                TextView emailView = (TextView) friendListItem.findViewById(R.id.email_view);
                emailView.setText(friendData.getEmail());
            }
            return friendListItem;
        }

        @Override
        public int getCount()
        {
            return FriendsEmailAddressesDao.getInstance().getSize();
        }

        @Override
        public Object getItem(int position)
        {
            return FriendsEmailAddressesDao.getInstance().get(position);
        }
        
    }
}
